package cn.fzhui.servlet;

import cn.fzhui.model.Admin;
import cn.fzhui.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        LoginService loginService = new LoginService();
        HttpSession session = req.getSession();
        try {
            // 登陆失败
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            if (loginService.login(new Admin(username, password))) {
                resp.sendRedirect("/index");
                session.setAttribute("username", req.getParameter("username"));
            } else {
                req.setAttribute("message", "账号或密码错误！");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }

        } catch (SQLException exception) {
            exception.printStackTrace();
        }

        return;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
